<template>
  <div class="profile-container">
    <div class="profile-content">
      <div class="profile-header">
        <h2>个人设置</h2>
        <p>管理您的账户信息</p>
      </div>

      <!-- 用户信息显示 -->
      <el-card class="profile-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        
        <div class="user-info">
          <div class="info-item">
            <label>用户ID:</label>
            <span>{{ userStore.userId }}</span>
          </div>
          <div class="info-item">
            <label>邮箱:</label>
            <span>{{ userStore.email }}</span>
          </div>
          <div class="info-item">
            <label>当前用户名:</label>
            <span>{{ userStore.username }}</span>
          </div>
        </div>
      </el-card>

      <!-- 修改用户名 -->
      <el-card class="profile-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>修改用户名</span>
          </div>
        </template>
        
        <el-form
          ref="usernameFormRef"
          :model="usernameForm"
          :rules="usernameRules"
          :label-position="labelPosition"
          label-width="120px"
          class="profile-form"
        >
          <el-form-item label="新用户名" prop="username">
            <el-input
              v-model="usernameForm.username"
              placeholder="请输入新用户名"
              size="large"
              :maxlength="50"
              show-word-limit
              autocomplete="username"
              autocapitalize="off"
              autocorrect="off"
              spellcheck="false"
            />
            <div class="form-tip">
              用户名只能包含字母、数字、点号、横线和下划线，长度3-50字符
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              :loading="usernameLoading"
              @click="handleUpdateUsername"
            >
              {{ usernameLoading ? '更新中...' : '更新用户名' }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 修改密码 -->
      <el-card class="profile-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>修改密码</span>
          </div>
        </template>
        
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          :label-position="labelPosition"
          label-width="120px"
          class="profile-form"
        >
          <el-form-item v-if="hasPassword" label="当前密码" prop="currentPassword">
            <el-input
              v-model="passwordForm.currentPassword"
              type="password"
              placeholder="请输入当前密码"
              size="large"
              show-password
              autocomplete="current-password"
            />
          </el-form-item>
          
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              size="large"
              show-password
              autocomplete="new-password"
            />
            <div class="form-tip">密码长度至少6位字符</div>
          </el-form-item>
          
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              size="large"
              show-password
              autocomplete="new-password"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              :loading="passwordLoading"
              :disabled="!profileReady"
              @click="handleUpdatePassword"
            >
              {{ passwordLoading ? '更新中...' : (hasPassword ? '修改密码' : '设置密码') }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getUserProfile, updateUsername, updatePassword } from '@/apis/user'
import { useUserStore } from '@/store/user'

const router = useRouter()
const userStore = useUserStore()

// 表单引用
const usernameFormRef = ref()
const passwordFormRef = ref()

// 用户信息
const userProfile = ref(null)

// 用户名修改表单
const usernameForm = reactive({
  username: ''
})

// 密码修改表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 加载状态
const usernameLoading = ref(false)
const passwordLoading = ref(false)

// 自适应表单标签位置：移动端置顶
const labelPosition = ref('right')
const updateLabelPosition = () => {
  labelPosition.value = window.innerWidth <= 768 ? 'top' : 'right'
}

// 计算属性：用户是否设置了密码（兼容无 hasPassword 字段的后端返回）
const hasPassword = computed(() => {
  const profile = userProfile.value
  if (!profile) return false
  if (typeof profile.hasPassword === 'boolean') {
    return profile.hasPassword
  }
  // 兼容旧版：若返回包含 password 且非空，视为已设置密码
  return profile.password !== null && profile.password !== undefined && profile.password !== ''
})

// 页面数据是否已就绪
const profileReady = computed(() => !!userProfile.value)

// 用户名验证规则
const usernameRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度为3-50字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9._-]+$/, message: '用户名只能包含字母、数字、点号、横线和下划线', trigger: 'blur' }
  ]
}

// 密码验证规则
const passwordRules = computed(() => {
  const rules = {
    newPassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 6, message: '密码长度至少6位', trigger: 'blur' }
    ],
    confirmPassword: [
      { required: true, message: '请确认新密码', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value !== passwordForm.newPassword) {
            callback(new Error('两次输入的密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }
  
  // 如果用户有密码，需要验证当前密码
  if (hasPassword.value) {
    rules.currentPassword = [
      { required: true, message: '请输入当前密码', trigger: 'blur' }
    ]
  }
  
  return rules
})

// 获取用户信息
const fetchUserProfile = async () => {
  try {
    const response = await getUserProfile()
    if (response.code === 200) {
      userProfile.value = response.data
      // 初始化用户名表单
      usernameForm.username = response.data.username
    } else {
      ElMessage.error(response.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('Fetch user profile error:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 更新用户名
const handleUpdateUsername = async () => {
  if (!usernameFormRef.value) return
  
  try {
    const valid = await usernameFormRef.value.validate()
    if (!valid) return
    
    // 检查是否与当前用户名相同
    if (usernameForm.username === userStore.username) {
      ElMessage.warning('新用户名与当前用户名相同')
      return
    }
    
    usernameLoading.value = true
    
    const response = await updateUsername({ username: usernameForm.username })
    
    if (response.code === 200) {
      ElMessage.success('用户名更新成功')
      
      // 更新本地存储的用户信息
      userStore.updateUserInfo({
        username: response.data.username
      })
      
      // 刷新用户信息
      await fetchUserProfile()
    } else {
      ElMessage.error(response.message || '用户名更新失败')
    }
  } catch (error) {
    console.error('Update username error:', error)
    ElMessage.error('用户名更新失败，请稍后重试')
  } finally {
    usernameLoading.value = false
  }
}

// 更新密码
const handleUpdatePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    // 必须等待用户信息加载完成，避免误判是否需要当前密码
    if (!profileReady.value) {
      ElMessage.warning('正在获取用户信息，请稍后重试')
      return
    }

    // 若已有密码但未输入当前密码，直接阻止提交
    if (hasPassword.value && !passwordForm.currentPassword) {
      ElMessage.error('请输入当前密码')
      return
    }

    const valid = await passwordFormRef.value.validate()
    if (!valid) return
    
    passwordLoading.value = true
    
    const requestData = {
      newPassword: passwordForm.newPassword,
      confirmPassword: passwordForm.confirmPassword
    }
    
    // 如果用户有密码，需要提供当前密码
    if (hasPassword.value) {
      requestData.currentPassword = passwordForm.currentPassword
    }
    
    const response = await updatePassword(requestData)
    
    if (response.code === 200) {
      ElMessage.success(hasPassword.value ? '密码修改成功' : '密码设置成功')
      
      // 清空表单
      passwordForm.currentPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
      
      // 刷新用户信息
      await fetchUserProfile()
    } else {
      ElMessage.error(response.message || '密码更新失败')
    }
  } catch (error) {
    console.error('Update password error:', error)
    ElMessage.error('密码更新失败，请稍后重试')
  } finally {
    passwordLoading.value = false
  }
}

// 页面初始化
onMounted(() => {
  updateLabelPosition()
  window.addEventListener('resize', updateLabelPosition)
  fetchUserProfile()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', updateLabelPosition)
})
</script>

<style scoped>
.profile-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: #f5f5f5;
  overflow-y: auto;
  box-sizing: border-box;
  margin: 0;
  padding: 20px;
}

.profile-content {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px 0;
}

/* 中等屏幕适配 */
@media (min-width: 768px) and (max-width: 1024px) {
  .profile-content {
    max-width: 600px;
    padding: 15px;
  }
  
  .profile-form {
    padding: 15px 0;
  }
  
  :deep(.el-form-item__label) {
    width: 140px;
  }
}

/* 大屏幕适配 */
@media (min-width: 1024px) {
  .profile-content {
    max-width: 800px;
    padding: 30px;
  }
  
  .profile-form {
    padding: 20px 0;
  }
}

.profile-header {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.profile-header h2 {
  font-size: 28px;
  margin-bottom: 10px;
}

.profile-header p {
  color: #666;
  font-size: 14px;
}

.profile-card {
  margin-bottom: 20px;
  border-radius: 10px;
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.user-info {
  padding: 10px 0;
}

.info-item {
  display: flex;
  margin-bottom: 15px;
  align-items: center;
}

.info-item label {
  width: 120px;
  font-weight: 500;
  color: #666;
  flex-shrink: 0;
}

.info-item span {
  color: #333;
  font-size: 14px;
}

.profile-form {
  padding: 10px 0;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-container {
    padding: 10px;
  }
  
  .profile-content {
    padding: 10px 0;
  }
  
  .profile-header h2 {
    font-size: 24px;
  }
  
  .profile-card {
    margin-bottom: 15px;
    border-radius: 8px;
  }
  
  .profile-card :deep(.el-card__body) {
    padding: 15px;
  }
  
  .card-header {
    font-size: 16px;
  }
  
  .profile-form {
    padding: 5px 0;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
    margin-bottom: 12px;
    padding: 8px 0;
  }
  
  .info-item label {
    width: auto;
    margin-bottom: 5px;
    font-size: 13px;
  }
  
  .info-item span {
    font-size: 14px;
    font-weight: 500;
  }
  
  :deep(.el-form-item) {
    margin-bottom: 15px;
  }
  
  :deep(.el-form-item__label) {
    width: 100% !important;
    text-align: left !important;
    margin-bottom: 8px;
    font-size: 14px;
    line-height: 1.5;
  }
  
  :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }
  
  :deep(.el-input) {
    width: 100%;
  }
  
  :deep(.el-button) {
    width: 100%;
    height: 44px;
    font-size: 16px;
  }
  
  .form-tip {
    font-size: 11px;
    margin-top: 8px;
    padding: 5px 8px;
    background: #f8f9fa;
    border-radius: 4px;
    line-height: 1.4;
  }
}

/* 小屏幕优化 */
@media (max-width: 480px) {
  .profile-container {
    padding: 5px;
  }
  
  .profile-header {
    margin-bottom: 20px;
  }
  
  .profile-header h2 {
    font-size: 20px;
  }
  
  .profile-header p {
    font-size: 12px;
  }
  
  .profile-card :deep(.el-card__header) {
    padding: 12px 15px;
  }
  
  .profile-card :deep(.el-card__body) {
    padding: 12px;
  }
  
  .card-header {
    font-size: 15px;
  }
  
  :deep(.el-form-item__label) {
    font-size: 13px;
  }
  
  :deep(.el-input__wrapper) {
    padding: 10px 12px;
  }
  
  /* 移动端触摸优化 */
  :deep(.el-input__inner) {
    font-size: 16px; /* 防止 iOS 缩放 */
  }
  
  :deep(.el-button) {
    min-height: 44px; /* iOS 推荐的最小触摸目标 */
    font-size: 16px;
  }
  
  .info-item {
    padding: 6px 0;
    margin-bottom: 10px;
  }
  
  .info-item label {
    font-size: 12px;
    margin-bottom: 4px;
  }
  
  .info-item span {
    font-size: 13px;
  }
}
</style>